// 外卖模块Store

import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

// 创建Store
const foodsStore = createSlice({
    name: 'foods',
    // Data
    initialState: {
        // 商品列表
        foodsList: [],
        // 选中的导航
        activeIndex: 0,
        // 购物车列表
        cartList: []
    },
    // Action
    reducers: {
        // 获取商品列表
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        // 更改导航
        updataActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        // 添加购物车列表
        addCartList(state, action) {
            // 查找是否已存在，存在则累加，不存在才添加
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        // 添加购物车数据
        plusCartList(state, action) {
            state.cartList.find(item => item.id === action.payload.id).count++
        },
        decrCartList(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item.count > 1) {
                item.count--
            } else {
                // 购物车删除商品
                state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
                return
            }
        },
        // 清除购物车
        DelCartList(state) {
            state.cartList = []
        }
    }
})

// 解构Action
const { setFoodsList, updataActiveIndex, addCartList, plusCartList, decrCartList, DelCartList } = foodsStore.actions

// 创建异步获取商品函数
const getFoodsListFunction = () => {
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3004/takeaway')
        // 调用Action传递Data
        dispatch(setFoodsList(res.data))
    }
}

// 导出Action和异步获取商品函数
export { getFoodsListFunction, updataActiveIndex, addCartList, plusCartList, decrCartList, DelCartList }
export default foodsStore.reducer
